package com.niit.project.controller;

import com.niit.project.entity.Goods;
import com.niit.project.entity.UserGoods;
import com.niit.project.service.GoodsService;
import com.niit.project.service.UserGoodsService;
import com.niit.project.service.impl.GoodsServiceImpl;
import com.niit.project.service.impl.UserGoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;

//宋依琳——用户上架商品
@WebServlet(name = "InsertController", value = "/InsertGoodsController")
@MultipartConfig(maxFileSize = 1024*1024*100,maxRequestSize = 1024*1024*200)
public class InsertGoodsController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //在用户添加商品时,也要将新数据添加到交易广场上
        String username = request.getParameter("username");
        System.out.println(username);
        String goodname = request.getParameter("goodname");
        String goodtype = request.getParameter("goodtype");
        String changemedium = request.getParameter("changemedium");
        String changeway = request.getParameter("changeway");
//        此处为用户上架商品时添加的图片
        Part part = request.getPart("goodimg");
//        //获取上传文件的数据  真实路径
        String uploadPath = request.getServletContext().getRealPath("assets/images/prv");
        File file = new File(uploadPath);
//        //判断文件夹是否存在,如果不存在则新建一个文件夹
        if(!file.exists())
        {
            file.mkdirs();  //新建文件夹
        }
//         //文件上传
        part.write(uploadPath+"\\"+part.getSubmittedFileName());
        //响应客户端 上传成功！
        System.out.println("上传成功");

        //将接收到的数据存储到userGoods中
        UserGoods userGoods = new UserGoods(username,goodname,goodtype,changemedium,changeway);
        UserGoodsService userGoodsService = new UserGoodsServiceImpl();
        //调用userGoodsService的addGoods方法，进行用户页面的商品添加
        userGoodsService.addGoods(userGoods);
        Goods goods = new Goods(username,goodname,goodtype,changemedium,changeway);
        GoodsService goodsService = new GoodsServiceImpl();
        //调用goodsService的addGoods方法，进行管理员页面的商品添加
        goodsService.addGoods(goods);

        //将添加图片的文件名存储到imaname中
        String imgname = part.getSubmittedFileName();
        System.out.println(imgname);
        request.setAttribute("imgname",imgname);
        response.sendRedirect(request.getContextPath()+"/UserSelfGoodsController");
    }
}
